<!--
 * @FilePath: Api_env.vue
 * @@author: wjj
 * @Date: 2025-10-14 20:06:05
 * @@Description: new js file
-->
<template>
  <el-card
    style="
      height: 65px;
      border-radius: 35px;
      background-color: rgb(204, 214, 225, 0);
    "
    class="card_class"
    :class="{ folded: LayOutSettingStore.fold }"
  >
    <div style="display: flex; justify-content: space-between; height: 100%">
      <el-form :inline="true">
        <el-form-item>
          <el-button
            type="primary"
            size="default"
            @click="addenv"
            style="border-radius: 10px"
          >
            <el-icon style="margin-right: 5px"><Plus /></el-icon>
            新增项目
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
  <el-card
    style="
      margin: 10px 0px;
      border-radius: 35px;
      background-color: rgb(204, 214, 225, 0);
    "
    class="card_class"
    :class="{ folded: LayOutSettingStore.fold }"
  >
    <!-- table展示用户信息 -->
    <el-table
      style="width: 100%"
      :data="apiEnvData"
      :row-class-name="tableRowClassName"
      height="550"
    >
      <el-table-column
        label="项目名称"
        align="center"
        prop="envProjectName"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.envProjectName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建人"
        align="center"
        prop="createEnvUserName"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.createEnvUserName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        show-overflow-tooltip
        prop="createEnvTime"
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.createEnvTime }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="BaseURL"
        align="center"
        prop="BaseURL"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.BaseURL }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="环境变量"
        align="center"
        prop="envVariable"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.envVariable }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="项目组件"
        align="center"
        prop="environment_Project"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span class="span_dark">
            {{ scope.row.envComponent }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <!-- eslint-disable -->
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            @click="selectEnv(row)"
            :disabled="
              row.envStatus ||
              (EnvStore.envName == row.envProjectName && firstEnvStatus)
            "
          >
            <el-icon><Switch /></el-icon>
            切换项目
          </el-button>
          <el-button
            type="primary"
            :icon="Edit"
            size="small"
            @click="editEnv(row)"
          ></el-button>
          <el-popconfirm
            class="box-item"
            :title="`确定删除${row.envProjectName}吗?`"
            placement="bottom"
            @confirm="deleteEnv(row)"
          >
            <template #reference>
              <el-button type="danger" :icon="Delete" size="small"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100, 200, 500]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHas"
      @size-change="handler"
    />
  </el-card>
  <!-- 编辑项目弹窗 -->
  <el-dialog
    v-model="envDialogStatus"
    :title="`${envFormData.id ? '编辑' : '新增'}项目 `"
    width="900px"
    class="api-case-dialog"
    draggable
    top="1vh"
  >
    <el-form :model="envFormData" label-width="120px" class="form-grid">
      <el-form-item label="项目名称" class="full-width">
        <el-input v-model="envFormData.envProjectName" placeholder="" />
      </el-form-item>

      <el-form-item label="BaseURL">
        <el-input v-model="envFormData.BaseURL" placeholder="项目域名" />
      </el-form-item>

      <el-form-item label="环境变量">
        <el-input
          v-model="envFormData.envVariable"
          placeholder=""
          type="textarea"
          :rows="8"
        />
      </el-form-item>

      <el-form-item label="项目组件" class="full-width">
        <el-input
          v-model="envFormData.envComponent"
          placeholder=""
          type="textarea"
          :rows="8"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="handleEnvSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang='ts' setup >
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
import useSocketClient from '@/store/socket/socket_client'
import emmit from '@/utils/emitter'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'
// 挂载完毕
//onMounted(()=>{})
//监控数据
//watch(select, (newVal, oldVal) => {})
import useLayOutSettingStore from '@/store/modules/setting'
import apiEnvStore from '@/store/modules/api_env'
import { ref, onMounted } from 'vue'
import {
  reqGetApiPreject,
  reqPostApiPreject,
  reqPutApiPreject,
  reqDeleteApiPreject,
  reqGetOneApiPreject,
} from '@/api/api_auto/project'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import { jsx } from 'vue/jsx-runtime'
import { number } from 'echarts'
defineOptions({
  name: 'InterfaceEnv',
})
let LayOutSettingStore = useLayOutSettingStore()

let EnvStore = apiEnvStore()
//默认页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(10)
//用户总个数
let total = ref<number>(0)
//存储全部用户的数组
let apiEnvData = ref<any>([])

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  return 'row_class'
}

//定义响应式数据:收集用户输入进来的关键字
let keyword = ref<string>('')
//获取模板setting仓库
//本地初始化项目数据
let firstEnvStatus = ref(false)
const reset = async () => {
  let envId = localStorage.getItem('envId')
  if (envId) {
    let result = await reqGetOneApiPreject(parseInt(envId))
    if (result.code == 200) {
      EnvStore.envName = result.data.envProjectName
      EnvStore.envId = result.data.id
      EnvStore.BaseURL = result.data.BaseURL
      EnvStore.envVariable = JSON.parse(result.data.envVariable)
      EnvStore.envComponent = JSON.parse(result.data.envComponent)
      firstEnvStatus.value = true
    } else {
      ElMessage.error(result.msg)
    }
  }
  // localStorage.removeItem('envId')
}
//组件挂载完毕
onMounted(() => {
  getHas()
  reset()
})
//获取全部信息
const getHas = async (pager = 1, asc = 'desc') => {
  //收集当前页码
  pageNo.value = pager
  let result = await reqGetApiPreject(
    pageNo.value,
    pageSize.value,
    keyword.value,
    asc,
  )
  if (result.code == 200) {
    total.value = result.data.total

    apiEnvData.value = result.data.apiEnvData
    for (let index = 0; index < apiEnvData.value.length; index++) {
      const element = apiEnvData.value[index]
      element.envStatus = false
    }
    console.log(apiEnvData.value)
  }
}
//分页器下拉菜单的自定义事件的回调
const handler = () => {
  getHas()
}
//编辑项目
const route = useRoute()
const router = useRouter()
let envFormData = ref<any>({})
let envDialogStatus = ref(false)
const cancelEdit = () => {
  envDialogStatus.value = false
}
const handleEnvSave = async () => {
  if (!envFormData.value.envProjectName) {
    ElMessage.error('项目名称不能为空')
    return
  }
  // 处理请求参数
  try {
    if (envFormData.value.envVariable.trim()) {
      JSON.parse(envFormData.value.envVariable)
    }
  } catch (error) {
    ElMessage.error('请求参数格式错误，请输入有效的JSON')
    return
  }
  // 处理请求参数
  try {
    if (envFormData.value.envComponent.trim()) {
      JSON.parse(envFormData.value.envComponent)
    }
  } catch (error) {
    ElMessage.error('请求参数格式错误，请输入有效的JSON')
    return
  }
  let result
  if (envFormData.value.id) {
    result = await reqPutApiPreject(envFormData.value)
  } else {
    result = await reqPostApiPreject(envFormData.value)
  }

  if (result.code == 200) {
    console.log(result)
    ElMessage.success(result.msg)
    envDialogStatus.value = false
    getHas()
  } else {
    ElMessage.error(result.msg)
  }
}
const selectEnv = (row: any) => {
  for (let index = 0; index < apiEnvData.value.length; index++) {
    const element = apiEnvData.value[index]
    element.envStatus = false
  }
  row.envStatus = true
  EnvStore.envName = row.envProjectName
  EnvStore.envId = row.id
  EnvStore.envVariable = JSON.parse(row.envVariable)
  EnvStore.envComponent = JSON.parse(row.envComponent)
  EnvStore.BaseURL = row.BaseURL
  localStorage.setItem('envId', String(EnvStore.envId))

  router.push({
    name: 'InterfaceAllCase',
    query: { id: 'asdasd' },
  })
}
//编辑项目
const editEnv = (row: any) => {
  envFormData.value = row
  envDialogStatus.value = true
}
//删除项目
const deleteEnv = async (row: any) => {
  let result = await reqDeleteApiPreject(row.id)
  if (result.code == 200) {
    ElMessage.success(result.msg)
    envDialogStatus.value = false
    getHas()
  } else {
    ElMessage.error(result.msg)
  }
}
//新增项目
const addenv = () => {
  envFormData.value = {}
  envDialogStatus.value = true
  console.log(EnvStore.envName)
}
</script>
<style>
</style>
<style scoped lang='scss'>
:deep(.row_class) {
  --el-table-border-color: rgba(220, 125, 177, 0.5);
}
.span_dark {
  color: #8d99ae;
}
.card_class {
  max-width: max(1250px, calc(100vw - 250px));
}
.card_class.folded {
  max-width: max(1250px, calc(100vw - 100px)); /* 折叠状态 */
}
.el-table .success-row {
  --el-table-tr-bg-color: rgba(125, 220, 135, 0.5);
}

.form {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
:deep(.danger-row) {
  background-color: #fef0f0;
}

:deep(.danger-row:hover) {
  background-color: #fde2e2;
}
:deep(.el-table__row:hover) {
  background-color: #f0f9ff;
  cursor: pointer;
}
</style>